package cn.vire.electric.simulation.utils;

import cn.vire.electric.simulation.pojo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author maple
 * @Description:
 * @date 2020/12/8 22:09
 */
@Slf4j
public class FileUtils {

    public static void outputPngImg(MultipartFile uploadFile,File targetFile) throws IOException {
        //将所有图片格式，重命名为.jpg
        String originalFilename = uploadFile.getOriginalFilename();
        if (!originalFilename.endsWith(".png")) {
            BufferedImage image = ImageIO.read(uploadFile.getInputStream());
            ImageIO.write(image, "png", targetFile);
        } else {
            //5.文件实现上传
            uploadFile.transferTo(targetFile);
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param path
     * @return
     */
    public static boolean fileIsExist(String path) {
        File file = new File(path);
        return file.exists();
    }

    /**
     * 获取图片的像素值 长和宽
     *
     * @return
     */
    public static FileVo getImgPixel(String imgPath) {
        File file = new File(imgPath);
        if (!file.exists()) {
            return null;
        }
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int width = bi.getWidth(); // 像素 宽度
        int height = bi.getHeight(); // 像素 长度
        FileVo fileVo = new FileVo();
        fileVo.setImgWidth(width);
        fileVo.setImgLength(height);
        return fileVo;

    }

    /**
     * @param fileUrl
     * @return
     */
    public static boolean deleteFile(String fileUrl) {
        File file = new File(fileUrl);
        if (!file.exists()) {
            return false;
        }
        return file.delete();
    }

    /**
     * 读取文件最后几行 <br>
     * 相当于Linux系统中的tail命令 读取大小限制是2GB
     *
     * @param filename 文件名
     * @param rows     读取行数
     * @return Pair<Long, List < String>>: 一对数据<行号,多行内容集合>
     */
    public static Pair<Long, List<String>> readLastRows(String filename, int rows) {
        File file = new File(filename);
        if (!file.exists()) {
            return null;
        }
        try (RandomAccessFile rf = new RandomAccessFile(file, "r")) {
            String separator = System.getProperty("line.separator");
            byte[] lineSeparator = separator.getBytes();
            // 每次读取的字节数要和系统换行符大小一致
            byte[] c = new byte[lineSeparator.length];
            // 在获取到指定行数和读完文档之前,从文档末尾向前移动指针,遍历文档每一个字节
            for (long pointer = rf.length(), lineSeparatorNum = 0; pointer >= 0 && lineSeparatorNum < rows; ) {
                // 移动指针
                rf.seek(pointer--);
                // 读取数据
                int readLength = rf.read(c);
                if (readLength != -1 && Arrays.equals(lineSeparator, c)) {
                    lineSeparatorNum++;
                }
                //扫描完依然没有找到足够的行数,将指针归0
                if (pointer == -1 && lineSeparatorNum < rows) {
                    rf.seek(0);
                }
            }
            byte[] tempbytes = new byte[(int) (rf.length() - rf.getFilePointer())];
            rf.readFully(tempbytes);
            String str = new String(tempbytes);
            String[] split = str.split(separator);
            return Pair.of(rf.getFilePointer(), Arrays.asList(split));
        } catch (Exception e) {
            log.error("readLastRows读取文件异常捕获", e);
            return null;
        }
    }

    public static void main(String[] args) {
        try (RandomAccessFile rf = new RandomAccessFile(new File("./logs/007/test"), "r")) {
            long historyRow = 0;
            ArrayList<String> strs = new ArrayList<>();
            while (true) {
                //获取RandomAccessFile对象文件指针的位置，初始位置是0
//                log.info("RandomAccessFile文件指针的初始位置:" + historyRow);
//                rf.seek(historyRow);//移动文件指针位置
                String tmp = "";
                while (rf.length() <= rf.getFilePointer()) {

                }
                log.info(historyRow+"+"+rf.length());
                while ((tmp = rf.readLine()) != null) {
                    strs.add(tmp);
                    historyRow = rf.getFilePointer();
                }
                if (!strs.isEmpty()) {
                    log.info(historyRow+"_"+rf.length());
                    log.info(strs.toString());
                    strs.clear();
                }
            }

        } catch (Exception e) {
            log.error("读取文件异常捕获", e);
        }
    }

    /**
     * 读取文件historyRow行后面的内容,相当于续读
     * @param file   文件名
     * @param historyRow 历史读取行数
     * @return null: 异常报错; List<String> :包含空行
     */
    public static Pair<Long, List<String>> readNewRows(File file, long historyRow) {
        if (!file.exists()) {
            return null;
        }
        try (RandomAccessFile rf = new RandomAccessFile(file, "r")) {
            long len = rf.length();
            ArrayList<String> strs = new ArrayList<>();
            if (len < historyRow) {
                log.info("Log file was reset. Restarting logging from start of file.");
                historyRow = 0;
            } else {
                //获取RandomAccessFile对象文件指针的位置，初始位置是0
                log.info("RandomAccessFile文件指针的初始位置:" + historyRow);
                rf.seek(historyRow);//移动文件指针位置
                String tmp = "";
                while ((tmp = rf.readLine()) != null) {
//                    String content = new String(tmp.getBytes("utf-8"));
                    strs.add(tmp);
                    historyRow = rf.getFilePointer();
                }
            }
            return Pair.of(historyRow, strs);
        } catch (Exception e) {
            log.error("读取文件异常捕获", e);
            return null;
        }
    }

    public static Pair<Long, List<String>> readNewRows(String filename, long historyRow) {
        return readNewRows(new File(filename), historyRow);
    }

    /**
     * 读取文件所有内容
     *
     * @param filename 文件名
     * @return null: 异常报错; List<String> :包含空行
     */
    public static List<String> readAllRows(String filename) {
        File file = new File(filename);
        if (!file.exists()) {
            return null;
        }
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line = null;
            ArrayList<String> contents = new ArrayList<>();
            while ((line = bufferedReader.readLine()) != null) {
                contents.add(line);
            }
            return contents;
        } catch (Exception e) {
            log.error("读取文件异常捕获", e);
            return null;
        }
    }

}
